package com.tang.hawkmusic.activity.login;

import android.app.Application;
import android.content.Intent;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;

import com.tang.hawkmusic.api.ApiEngine;
import com.tang.hawkmusic.bean.UserInfo;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginViewModel extends AndroidViewModel {
    private UserInfo userInfo;
    LoginActivity loginActivity;
    public LoginViewModel(@NonNull Application application) {
        super(application);
    }

    /*调用接口登录*/
    public void loginPhone(String phone,String password){
        Call<UserInfo> call= ApiEngine.getService().loginPhone(phone,password);
        call.enqueue(new Callback<UserInfo>() {
            @Override
            public void onResponse(Call<UserInfo> call, Response<UserInfo> response) {
                userInfo=response.body();
                if (isSuccess()){
                    Intent data=new Intent();
                    data.putExtra("userInfo",getUserInfo());
                    loginActivity.setResult(1,data);
                    loginActivity.showToast("登录改成");
                    loginActivity.finish();
                }else loginActivity.showToast("登录失败");
            }

            @Override
            public void onFailure(Call<UserInfo> call, Throwable t) {
                userInfo=null;
            }
        });
    }
    public boolean isSuccess(){
        //userInfo的Code是200
        return userInfo != null && userInfo.getCode() == 200;
    }
    public UserInfo getUserInfo(){
        return userInfo;
    }

    public void setLoginActivity(LoginActivity loginActivity) {
        this.loginActivity = loginActivity;
    }
}
